package com.jsn.baselibx.widget

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import com.jsn.baselibx.util.showMessage
import java.util.*
import kotlin.collections.ArrayList

abstract  class BaseRVAdapter<T,VH:BaseViewHolder>(val context: Context)
    :RecyclerView.Adapter<VH>() {

    var items= mutableListOf<T>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
        layoutResId(viewType).also {
            val binding=DataBindingUtil.inflate<ViewDataBinding>(LayoutInflater.from(parent.context),it,parent,false) //返回的是ViewDatabinding
            return holderInstance(binding)
        }
    }

    override fun onBindViewHolder(holder: VH, position: Int) {
        holder.itemView?.apply {  //itemview 设置点击事件
            setOnClickListener{
                holder.doClick(it)
            }
        }
        holder._position=position //注意position在这里注入
        holder.bindData(getItem(position))
    }

    /**
     * @param viewType According to position return item layout id
     */
    abstract fun layoutResId(viewType: Int): Int


    /**
     * ViewHolder实例化
     */
    abstract fun holderInstance(binding: ViewDataBinding): VH

    override fun getItemCount(): Int {
       return items.size
    }

    /*集合操作*/  //todo 使用DiffUtil
    fun getItem(position: Int):T =items.get(position)

    fun setData(items:ArrayList<T>){
        this.items.clear()
        this.items.addAll(items)
        notifyDataSetChanged()
    }

    fun insert(position: Int, item: T) {
        items.add(position, item)
        notifyDataSetChanged()
    }


    fun remove(position: Int) {
        try{
            val remove = items.removeAt(position)
            if (remove != null) {
                notifyDataSetChanged()
            }
        }catch (e:Throwable){
            e.message?.let { context.applicationContext.showMessage(it) }
        }finally {

        }
    }

    fun replace(position: Int, item: T) {
        Collections.replaceAll(items, getItem(position), item)
        notifyDataSetChanged()
    }

    fun clear() {
        this.items.clear()
        notifyDataSetChanged()
    }



}